package com.itheima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.itheima.admin.pojo.AdUser;
import com.itheima.admin.mapper.AdUserMapper;
import com.itheima.admin.service.AdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.AppJwtUtil;
import org.apache.tomcat.jni.Thread;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @description <p>管理员用户信息 业务实现</p>
 *
 * @version 1.0
 * @package com.itheima.admin.service.impl
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Override
    public Map<String, Object> login(Map<String, String> resultMap) {
        //1.获取参数
        String name = resultMap.get("name");
        String pwd = resultMap.get("password");
        //2.参数非空判断
        if (!StringUtils.isNotEmpty(name) || StringUtils.isNotEmpty(pwd)) {
            throw  new LeadNewsException("用户名或密码不能为空");
        }
        //3.通过登录名查询用户
        AdUser user = query().eq("name", name).one();
        if (null == user){
            throw new LeadNewsException("用户名或者密码错误");
        }
        //4.密码校验
        pwd += user.getSalt();
        //4.1 密码加盐后进行MD5
        String password = DigestUtils.md5DigestAsHex(pwd.getBytes());
        //4.2 校验密码是否相同，不同则报错
        if (user.getPassword().equals(password)){
            throw new LeadNewsException("用户名或者密码错误");
        }
        //5. 校验通过，生成token令牌
        String token = AppJwtUtil.createToken(user.getId());
        //6.构建结果并且返回
        Map<String,Object> map = new HashMap<>();

        map.put("token", token);
        map.put("user", user);
        return map;
    }

}
